package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import org.apache.poi.ss.formula.functions.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: AddressBookServiceImpl
 * @Author: YuanDing
 * @Date: 2024/2/7 11:56
 * @Description:
 */

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public Result list() {
        List<AddressBook> addressBookList = addressBookMapper.selectAllByUserId(BaseContext.getCurrentId());
        return Result.success(addressBookList);
    }

    @Override
    public Result getDefaultAddress() {
        AddressBook addressBook = addressBookMapper.selectUserDefaultAddress(BaseContext.getCurrentId());
        return Result.success(addressBook);
    }

    @Override
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insertAddress(addressBook);
    }

    @Override
    public void updateDefaultAddress(Long id) {
        AddressBook defaultAddress = addressBookMapper.selectUserDefaultAddress(BaseContext.getCurrentId());
        if (defaultAddress != null) {
            addressBookMapper.updateDefaultAddressById(defaultAddress.getId());
        }

        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .build();
        addressBookMapper.updateDefaultAddress(addressBook);
    }

    @Override
    public Result getAddressById(Long id) {
        AddressBook addressBook = addressBookMapper.selectAddressById(id);
        return Result.success(addressBook);
    }

    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    @Override
    public void delAddress(Long id) {
        addressBookMapper.deleteById(id);
    }
}
